//
// winter - Direct2D GUI framework.
// Copyright (C) 2009 Aleksandar Dezelin 
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef THREAD_SINGLETON_HOST_H
#define THREAD_SINGLETON_HOST_H

#pragma once
#include "noncopyable.h"
#include "synchronization.h"
#include <hash_map>
#include <memory>
#include <stdlib.h>
#include <Tlhelp32.h>
#include <Windows.h>

namespace winter {
namespace platform {

using namespace winter::services;

/// <summary>
///     Implements per-thread singleton using one-init Windows API.
/// </summmary>
template<class T>
class thread_singleton_host : public services::noncopyable {
public:

  /// <summary>
  ///     Returns and initializes the singleton instance on first call.
  /// </summary>
  /// <returns>
  ///     The singleton instance.
  /// </returns>
  static T* instance() {
    void* context;
    if(::InitOnceExecuteOnce(&_once, create_instance, NULL, &context))
      return static_cast<T*>(context);
    else
      return 0;
  }

  /// <summary>
  ///     Destroys the singleton instance.
  ///     NOTE: not thread safe.
  /// </summary>
  static void destroy() {
    // Convert stored pointer to instance pointer
    T* p = reinterpret_cast<T*>((reinterpret_cast<INT_PTR>(_once.Ptr) >> 
      RTL_RUN_ONCE_CTX_RESERVED_BITS) << RTL_RUN_ONCE_CTX_RESERVED_BITS);
    delete p;
    // Reset one-time initialization structure. 
    ::InitOnceInitialize(&_once);
  }

private:
  explicit thread_singleton_host();
  ~thread_singleton_host();

  static BOOL CALLBACK create_instance(PINIT_ONCE InitOnce, 
    PVOID Parameter, PVOID *lpContext) {
    try {
      std::auto_ptr<T> p(new T());
      schedule_for_destruction(destroy);
      *lpContext = p.release();
    } catch(...) {
      return FALSE;
    }

    return TRUE;

    UNREFERENCED_PARAMETER(InitOnce);
    UNREFERENCED_PARAMETER(Parameter);
  }

  static DWORD get_main_thread_id() {
    static DWORD thread_id = 0;

    if(thread_id == 0) {
      HANDLE snapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
      if(snapshot == INVALID_HANDLE_VALUE)
        return 0;

      THREADENTRY32 te32;
      memset(&te32, 0, sizeof(te32));
      te32.dwSize = sizeof(te32);
      if(!::Thread32First(snapshot, &te32)) {
        ::CloseHandle(snapshot);
        return 0;
      }

      DWORD process_id = ::GetCurrentProcessId();
      do {
        if(te32.th32OwnerProcessID == process_id) {
          thread_id = te32.th32ThreadID;
          break;
        }
      } while(::Thread32Next(snapshot, &te32));

      ::CloseHandle(snapshot);
    }

    return thread_id;
  }

  static void schedule_for_destruction(void (*destroy_fun)()) {
    DWORD thread_id = ::GetCurrentThreadId();
    DWORD main_thread_id = get_main_thread_id();
    WINTER_ASSERT(main_thread_id);

    if(thread_id == main_thread_id)
      std::atexit(destroy_fun);
    else {
      critical_section::scoped_lock lock(detail::g_ts_sync);
      detail::g_ts_dtors[thread_id] = destroy_fun;
    }
  }

  __declspec(thread) static INIT_ONCE _once;
};

template<class T>
INIT_ONCE thread_singleton_host<T>::_once = INIT_ONCE_STATIC_INIT;

namespace detail {

static critical_section g_ts_sync;
static std::hash_map<DWORD, void (*)()> g_ts_dtors;

static void NTAPI on_tls_callback(void* dll_handle, DWORD reason, void* reserved)
{
  if(reason != DLL_THREAD_DETACH)
    return;

  DWORD thread_id = ::GetCurrentThreadId();
  critical_section::scoped_lock lock(g_ts_sync);
  void (*destroy_fun)() = g_ts_dtors[thread_id];
  if(!destroy_fun)
    return;

  destroy_fun();
  g_ts_dtors[thread_id] = 0;

  UNREFERENCED_PARAMETER(dll_handle);
  UNREFERENCED_PARAMETER(reserved);
}

#pragma section(".CRT$XLB", read)
__declspec(allocate(".CRT$XLB")) PIMAGE_TLS_CALLBACK g_tls_callback = on_tls_callback;

}

}
}

#endif // THREAD_SINGLETON_HOST_H
